package q5_blocking_queue_test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//资源类
class ShareData {
    private int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() throws Exception {
        lock.lock();
        try {
            //1 判断
            while (num != 0) {
                //等待，不能生产
                condition.await();
            }
            //2 干活
            num++;
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            //3 通知唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws Exception {
        lock.lock();
        try {
            //1 判断
            while (num == 0) {
                //等待，不能消费
                condition.await();
            }
            //2 干活
            num--;
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            //3 通知唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

/**
 * 生产者消费者实现演示
 * <p>
 * 题目：一个初始值为零的变量，两个线程对其交替操作，一个加1一个减1，来5轮。
 * <p>
 * 1 线程 操作 资源类
 * 2 判断 干活 通知
 * 3 判断虚假唤醒机制
 */
public class ProducerConsumerTraditionDemo {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();


        new Thread(() -> {

            try {
                for (int i = 1; i <= 5; i++) {
                    shareData.increment();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "A").start();


        new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    shareData.decrement();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "B").start();
    }
}
